package com.wanxi.generictype.myarraylist;

import java.util.Arrays;

public class MyArrayList<E> implements MyList<E> {
    private static final int DEFAULT_CAPACITY = 10;
    private int size;
    private E[] elements;

    public MyArrayList() {
        this(DEFAULT_CAPACITY);//调的自身的有参构造方法。
    }

    public MyArrayList(int initialCapacity) {
        if (initialCapacity < 0) {
            throw new IllegalArgumentException("状态异常" + initialCapacity);
        }
        this.elements = (E[]) new Object[initialCapacity];//强转数组类型。

    }


    @Override
    public boolean add(E e) {//没有扩容的操作，，，，，，，，，，，
        elements[size] = e;
        size++;
        return true;
    }

    public void add(int index, E element) {//还需要理解一下
        if (index > size || index < 0) {
            throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size);
        }
        System.arraycopy(elements, index, elements, index + 1, size - index);
        elements[index] = element;
        size++;
    }


    @Override
    public E get(int index) {
        if (index >= size) {
            throw new IndexOutOfBoundsException("索引越界，" + "Index: " + index + ", Size: " + size);
        }
        return elements[index];
    }

    @Override
    public int size() {
        return size;
    }

    @Override
    public void clear() {
        for (int i = 0; i < elements.length; i++) {
            elements[i] = null;
        }
        size = 0;

    }

    @Override
    public String toString() {
        return "MyArrayList{" +
                "size=" + size +
                ", elements=" + Arrays.toString(elements) +
                '}';
    }
}
